/*
 * BatteryTesterView.java
 */
package batterytester;

import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import java.awt.event.WindowEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.TimerTask;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import listeners.IFKitAttachListener;
import listeners.IFKitDetachListener;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * The application's main frame.
 */
public class BatteryTesterView extends FrameView {

    // Phidget reads max 5 volts, so we're scaling our 12 volt battery
    // to 1/3 the voltage.
    private static final double kVoltageConversion = 15.0 / 1000;
    private InterfaceKitPhidget m_ifkPhidget;
    private IFKitAttachListener m_attachListener;
    private IFKitDetachListener m_detachListener;
    private XYSeriesCollection m_voltageDataset = new XYSeriesCollection();
    private XYSeries m_dataSeries;
    private int m_secondsTested = 0;
    private int m_secBetweenSamples;
    private int m_testTimeSec;
    private int m_noLoadTimeSec;
    private double m_stopVoltage;
    private java.util.Timer m_measurementTimer;
    private boolean m_batteryLoadOn;

    public BatteryTesterView(SingleFrameApplication app) {
        super(app);

        initComponents();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
        // Don't want the user to resize the Window.
        getFrame().setResizable(false);

        // Setup the phidget.
        try {
            m_ifkPhidget = new InterfaceKitPhidget();
            m_attachListener = new IFKitAttachListener(BatteryTesterApp.getApplication().getMainFrame(), txtPhidgetConnected, btnStart);
            m_detachListener = new IFKitDetachListener(BatteryTesterApp.getApplication().getMainFrame(), txtPhidgetConnected, btnStart);
            m_ifkPhidget.addAttachListener(m_attachListener);
            m_ifkPhidget.addDetachListener(m_detachListener);
            m_ifkPhidget.openAny();

        } catch (PhidgetException ex) {
            showPhidgetException(ex);
        }
        // Make chart ready to receive data.
        voltageChart.setDataset(m_voltageDataset);

        // Need to be able to detach the Phidget when the application is closed.
        getFrame().addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    m_ifkPhidget.removeDetachListener(m_detachListener);
                    m_ifkPhidget.removeAttachListener(m_attachListener);
                    //close the phidget
                    m_ifkPhidget.close();
                    m_ifkPhidget = null;
                    System.exit(0);
                } catch (PhidgetException ex) {
                    showPhidgetException(ex);
                }
            }
        });
    }

    private void showPhidgetException(PhidgetException ex) {
        JOptionPane.showMessageDialog(getFrame(), ex.getDescription(), "Phidget error " + ex.getErrorNumber(), JOptionPane.ERROR_MESSAGE);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = BatteryTesterApp.getApplication().getMainFrame();
            aboutBox = new BatteryTesterAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        BatteryTesterApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        spinSecBetweenSamples = new javax.swing.JSpinner();
        spinTestTimeSec = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        voltageChart = new org.jfree.beans.JLineChart();
        btnStart = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        txtFileName = new javax.swing.JTextField();
        txtID = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtPhidgetConnected = new javax.swing.JTextField();
        txtVoltage = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        spinNoLoadTimeSec = new javax.swing.JSpinner();
        spinStopVoltage = new javax.swing.JSpinner();
        jLabel9 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setMaximumSize(new java.awt.Dimension(897, 497));
        mainPanel.setMinimumSize(new java.awt.Dimension(897, 497));
        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(batterytester.BatteryTesterApp.class).getContext().getResourceMap(BatteryTesterView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        spinSecBetweenSamples.setModel(new javax.swing.SpinnerNumberModel(1, 1, 60, 1));
        spinSecBetweenSamples.setName("spinSecBetweenSamples"); // NOI18N

        spinTestTimeSec.setModel(new javax.swing.SpinnerNumberModel(180, 1, 600, 1));
        spinTestTimeSec.setName("spinTestTimeSec"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        voltageChart.setDataset(null);
        voltageChart.setName("voltageChart"); // NOI18N
        voltageChart.setSource(resourceMap.getString("voltageChart.source")); // NOI18N
        voltageChart.setSubtitle(resourceMap.getString("voltageChart.subtitle")); // NOI18N
        voltageChart.setTitle(resourceMap.getString("voltageChart.title")); // NOI18N
        voltageChart.setXAxisLabel(resourceMap.getString("voltageChart.xAxisLabel")); // NOI18N
        voltageChart.setYAxisLabel(resourceMap.getString("voltageChart.yAxisLabel")); // NOI18N

        javax.swing.GroupLayout voltageChartLayout = new javax.swing.GroupLayout(voltageChart);
        voltageChart.setLayout(voltageChartLayout);
        voltageChartLayout.setHorizontalGroup(
            voltageChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 654, Short.MAX_VALUE)
        );
        voltageChartLayout.setVerticalGroup(
            voltageChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 475, Short.MAX_VALUE)
        );

        btnStart.setText(resourceMap.getString("btnStart.text")); // NOI18N
        btnStart.setEnabled(false);
        btnStart.setName("btnStart"); // NOI18N
        btnStart.setPreferredSize(new java.awt.Dimension(55, 23));
        btnStart.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnStartMouseClicked(evt);
            }
        });

        btnStop.setText(resourceMap.getString("btnStop.text")); // NOI18N
        btnStop.setEnabled(false);
        btnStop.setName("btnStop"); // NOI18N
        btnStop.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnStopMouseClicked(evt);
            }
        });

        txtFileName.setText(resourceMap.getString("txtFileName.text")); // NOI18N
        txtFileName.setName("txtFileName"); // NOI18N

        txtID.setText(resourceMap.getString("txtID.text")); // NOI18N
        txtID.setName("txtID"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        txtPhidgetConnected.setText(resourceMap.getString("txtPhidgetConnected.text")); // NOI18N
        txtPhidgetConnected.setEnabled(false);

        txtVoltage.setFont(resourceMap.getFont("txtVoltage.font")); // NOI18N
        txtVoltage.setText(resourceMap.getString("txtVoltage.text")); // NOI18N
        txtVoltage.setEnabled(false);
        txtVoltage.setName("txtVoltage"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setFont(resourceMap.getFont("jLabel8.font")); // NOI18N
        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        spinNoLoadTimeSec.setModel(new javax.swing.SpinnerNumberModel(10, 0, 60, 1));
        spinNoLoadTimeSec.setName("spinNoLoadTimeSec"); // NOI18N

        spinStopVoltage.setModel(new javax.swing.SpinnerNumberModel(7.5d, 0.0d, 12.0d, 0.1d));
        spinStopVoltage.setName("spinStopVoltage"); // NOI18N

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel6)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                                        .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addComponent(jLabel8)
                                    .addGap(23, 23, 23))
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addComponent(jLabel9)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtVoltage)
                            .addComponent(txtID)
                            .addComponent(txtFileName, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
                            .addComponent(txtPhidgetConnected, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnStop, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(spinSecBetweenSamples, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(spinNoLoadTimeSec, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(spinStopVoltage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                                    .addComponent(spinTestTimeSec, javax.swing.GroupLayout.Alignment.TRAILING))))))
                .addGap(18, 18, 18)
                .addComponent(voltageChart, javax.swing.GroupLayout.PREFERRED_SIZE, 654, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtPhidgetConnected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(spinTestTimeSec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(spinSecBetweenSamples, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spinNoLoadTimeSec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(17, 17, 17)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spinStopVoltage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(21, 21, 21)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(72, 72, 72)
                        .addComponent(jLabel8))
                    .addComponent(txtVoltage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnStop))
                .addGap(34, 34, 34))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(voltageChart, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                .addContainerGap())
        );

        spinSecBetweenSamples.getAccessibleContext().setAccessibleName(resourceMap.getString("jSpinner2.AccessibleContext.accessibleName")); // NOI18N
        spinTestTimeSec.getAccessibleContext().setAccessibleName(resourceMap.getString("jSpinner3.AccessibleContext.accessibleName")); // NOI18N
        btnStart.getAccessibleContext().setAccessibleName(resourceMap.getString("jButton1.AccessibleContext.accessibleName")); // NOI18N
        btnStop.getAccessibleContext().setAccessibleName(resourceMap.getString("jButton2.AccessibleContext.accessibleName")); // NOI18N
        txtFileName.getAccessibleContext().setAccessibleName(resourceMap.getString("jTextField1.AccessibleContext.accessibleName")); // NOI18N
        txtID.getAccessibleContext().setAccessibleName(resourceMap.getString("jTextField2.AccessibleContext.accessibleName")); // NOI18N
        jLabel5.getAccessibleContext().setAccessibleName(resourceMap.getString("jLabel5.AccessibleContext.accessibleName")); // NOI18N
        txtPhidgetConnected.getAccessibleContext().setAccessibleName(resourceMap.getString("jTextField3.AccessibleContext.accessibleName")); // NOI18N
        spinStopVoltage.getAccessibleContext().setAccessibleName(resourceMap.getString("jSpinner1.AccessibleContext.accessibleName")); // NOI18N

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(batterytester.BatteryTesterApp.class).getContext().getActionMap(BatteryTesterView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 897, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 877, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(741, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel))
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void btnStartMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMouseClicked
        m_batteryLoadOn = false;
        m_secondsTested = 0;
        
        // Get all the user settings.
        m_secBetweenSamples = ((SpinnerNumberModel) spinSecBetweenSamples.getModel()).getNumber().intValue();
        m_testTimeSec = ((SpinnerNumberModel) spinTestTimeSec.getModel()).getNumber().intValue();
        m_noLoadTimeSec = ((SpinnerNumberModel) spinNoLoadTimeSec.getModel()).getNumber().intValue();
        m_stopVoltage = ((SpinnerNumberModel) spinStopVoltage.getModel()).getNumber().doubleValue();

        // Setup the data series.
        m_dataSeries = new XYSeries("");
        m_voltageDataset.removeAllSeries();
        m_voltageDataset.addSeries(m_dataSeries);

        try {
            // Only turn on the load if there is no time without it.
            if (0 == m_noLoadTimeSec) {
                m_ifkPhidget.setOutputState(0, true);
                m_batteryLoadOn = true;
            }
            m_ifkPhidget.setOutputState(1, true);
        } catch (PhidgetException ex) {
            showPhidgetException(ex);
        }
        btnStop.setEnabled(true);
        btnStart.setEnabled(false);

        //Test is run as a timer task to give even time between measurements.
        m_measurementTimer = new java.util.Timer();
        m_measurementTimer.schedule(new TimerTask() {
            public void run() {
                double measuredVoltage = 0;
                try {
                    measuredVoltage = kVoltageConversion * m_ifkPhidget.getSensorValue(0);
                } catch (PhidgetException ex) {
                    showPhidgetException(ex);
                }
                // Put the measurement on the graph.
                m_dataSeries.add(m_secondsTested, measuredVoltage);
                // Put the measurement in the textbox.
                txtVoltage.setText(String.valueOf(measuredVoltage));
                // Calculate the time of the next sample to get the next graph
                // X value.
                m_secondsTested += m_secBetweenSamples;

                // When the requested test length is reached or the voltage drops
                // below the stop voltage, stop the test.
                if (m_secondsTested > m_testTimeSec || measuredVoltage <= m_stopVoltage) {
                    endTest();
                } else if (!m_batteryLoadOn && m_secondsTested > m_noLoadTimeSec) {
                    // Turn on the battery load when the next measurements time says
                    // it should be under load. e.g. If time between measurements is 6
                    // and no load time is 20, the load will be turned on at 18.
                    try {
                        m_ifkPhidget.setOutputState(0, true);
                    } catch (PhidgetException ex) {
                        showPhidgetException(ex);
                    }
                    m_batteryLoadOn = true;
                }
            }
        }, 0, m_secBetweenSamples * 1000); // Time between samples in milliseconds.
    }//GEN-LAST:event_btnStartMouseClicked

    private void endTest() {
        // Turn off timer, so we don't take any more measurements.
        m_measurementTimer.cancel();
        btnStop.setEnabled(false);
        btnStart.setEnabled(true);
        // Turn off all power since we're done.
        try {
            m_ifkPhidget.setOutputState(0, false);
            m_ifkPhidget.setOutputState(1, false);
            m_batteryLoadOn = false;
        } catch (PhidgetException ex) {
            btnStart.setEnabled(false);
            showPhidgetException(ex);
        }
        // Get the filename from the name and ID.
        String filename = txtFileName.getText().trim() + txtID.getText().trim();
        if (filename.equals("")) {
            filename = "unknown";
        }
        filename = "c:\\BatteryData\\" + filename + ".csv";

        // Ask the user if they're sure they want to save the file.
        int optionResult = JOptionPane.showConfirmDialog(getFrame(),
                "Save data to " + filename + "?",
                "Save Data?",
                JOptionPane.YES_NO_OPTION);
        if (optionResult == JOptionPane.YES_OPTION) {
            // Make sure the directory exists.
            File d = new File("c:\\BatteryData\\");
            if (!d.exists()) {
                d.mkdir(); // Make directory if doesn't exist.
            }
            try {
                FileWriter outFile = new FileWriter(filename, true);
                PrintWriter out = new PrintWriter(outFile);

                // Write data to file
                out.println("Date," + (new Date()).toString());
                out.println("ID," + txtID.getText().trim());
                out.println("Test Requested Length," + String.valueOf(m_testTimeSec));
                out.println("Test Actual Length," + String.valueOf(m_secBetweenSamples * (m_dataSeries.getItemCount() - 1)));
                out.println("Sample Interval," + String.valueOf(m_secBetweenSamples));
                out.println("No Load Time," + String.valueOf(m_noLoadTimeSec));
                out.println("Stop Voltage," + String.valueOf(m_stopVoltage));
                out.println("");
                out.println("Seconds,Voltage");
                // Use the graph's data series to get the measurement times and
                // measured voltages.
                for (int i = 0; i < m_dataSeries.getItemCount(); i++) {
                    out.println(m_dataSeries.getX(i) + "," + m_dataSeries.getY(i));
                }
                out.println("");
                out.close();
                outFile.close();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(getFrame(), e.getMessage(), "Save File Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void btnStopMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStopMouseClicked
        endTest();
    }//GEN-LAST:event_btnStopMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStart;
    private javax.swing.JButton btnStop;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JSpinner spinNoLoadTimeSec;
    private javax.swing.JSpinner spinSecBetweenSamples;
    private javax.swing.JSpinner spinStopVoltage;
    private javax.swing.JSpinner spinTestTimeSec;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField txtFileName;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtPhidgetConnected;
    private javax.swing.JTextField txtVoltage;
    private org.jfree.beans.JLineChart voltageChart;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
